const mongoDbConfig = require('../../../config/mongodb.json');
const mongoose = require('mongoose');

let mongooseClient = null;

// DEBUG 模式
mongoose.set('debug', process.env.NODE_ENV === 'development');
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);

function selectDbName () {
    let dbName;
    switch (process.env.NODE_ENV) {
    case 'development':
        dbName = mongoDbConfig.dev_database;
        break;
    case 'trial':
        dbName = mongoDbConfig.dev_database;
        break;
    case 'release':
        dbName = mongoDbConfig.release_database;
        break;
    default:
        dbName = mongoDbConfig.dev_database;
    }
    if (!dbName) {
        throw new Error('未找到对应的数据库名称');
    }
    return dbName;
}

function getMongooseClient () {
    if (mongooseClient === null) {
        mongooseClient = mongoose.createConnection(mongoDbConfig.uri, {
            useNewUrlParser: true,
            poolSize: mongoDbConfig.pool_size,
            loggerLevel: 'error',
            useUnifiedTopology: true,
            keepAlive: mongoDbConfig.keep_alive,
            dbName: selectDbName()
        });
    }
    return mongooseClient;
}

function StringToObjectId (id) {
    return mongoose.Types.ObjectId(id);
}

module.exports = {
    getMongooseClient,
    MongooseSchema: mongoose.Schema,
    Model: mongoose.Model,
    MongooseDocument: mongoose.Document,
    Error: mongoose.Error,
    Connection: mongoose.Connection,
    StringToObjectId
};
